package com.example.springboot.service;

import cn.hutool.core.util.ObjectUtil;
import com.example.springboot.common.ResultCode;
import com.example.springboot.common.config.JwtTokenUtils;
import com.example.springboot.dao.GradeDao;
import com.example.springboot.entity.Account;
import com.example.springboot.entity.Grade;
import com.example.springboot.exception.CustomException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GradeService {

    @Resource
    GradeDao gradeDao;

    public List<Grade> getAll() {
        return gradeDao.selectAll();
    }

    public Grade findById(Integer id) {

        return gradeDao.findById(id);
    }

    public Grade gradeRegister(Grade grade) {

        String userName = grade.getGradeName();
//     1.先校验用户名是不是为空： 如果用户名，为空，抛出异常
        if (ObjectUtil.isEmpty(userName)){
            throw new CustomException(ResultCode.USERNAME_ISNULL);
        }
//     2.校验用户名的唯一性：
        Grade dbGrade = gradeDao.findByName(userName);
        if (ObjectUtil.isNotEmpty(dbGrade)) {
            throw new CustomException(ResultCode.USER_EXIST_ERROR);
        }
        gradeDao.insertSelective(grade);
        return grade;
    }

    public void delete(Integer id) {
        gradeDao.deleteByPrimaryKey(id);
    }


    public Grade gradeEdit(Grade grade) {

        String userName = grade.getGradeName();
//     1.先校验用户名是不是为空： 如果用户名，为空，抛出异常
        if (ObjectUtil.isEmpty(userName)){
            throw new CustomException(ResultCode.USERNAME_ISNULL);
        }
        gradeDao.updateByPrimaryKeySelective(grade);

        return grade;
    }

    // 分页查询和模糊查询的方法
    public PageInfo<Grade> findPage(Grade search, Integer pageNum, Integer pageSize) {
//        1.获取当前用户，判断当前用户是否登录状态
        Account user = JwtTokenUtils.getCurrentUser();
        if (ObjectUtil.isEmpty(user)) {
            throw new CustomException(ResultCode.USER_NOT_LOGIN);
        }

        // 2.开启分页：开启分页这一句代码，一定要在操作数据的方法
        PageHelper.startPage(pageNum, pageSize);
        List<Grade> all = findByCondition(search);

        return PageInfo.of(all);
    }

    // 根据条件查询的方法
    public List<Grade> findByCondition(Grade search) {
        return gradeDao.findBySearch(search);
    }
}
